var sys_schedule = {
    /**
     * 我的档期 初始化方法
     */
    init: function() {
        var _curDate1 = new Date();
        var _curDate = formatDate(_curDate1, 'yyyy年MM月');
        var _date_hide = formatDate(_curDate1, 'yyyy-MM');
        $('#schedule label b').text(_curDate).after('<input type="hidden" id="md_cur_date" value="' + _date_hide + '"/>');
        $.ajax({
            type: "get",
            url: "by/schedule",
            data: {
                "user_id": 0
            },
            error: function (e) {
                console.log(e);
            },
            success: function (ret) {
                sys_schedule.renderSchedule(new Date(_curDate1.getFullYear(), _curDate1.getMonth(), '01'), ret.scheduleData);
            }
        });
        this.bindDateEvent(0);
    },

    /**
     * 渲染商家档期展示页面
     * @param date 日期
     */
    renderSchedule: function(date, sche) {
        var _dateObj = formatDate(date, 'yyyy-MM');
        var _year = date.getFullYear();
        // 获取当前时间月份
        var _month = date.getMonth();
        _month = _month < 10 ? '0' + _month : _month;
        // 根据月份获取当前月份天数
        var days = getDateByMonth(_dateObj);
        $('#schedule .calendar h2:eq(0) em').remove();
        $('#schedule .calendar h2:eq(1) em').remove();
        $('#schedule .calendar h2:eq(2) em').remove();
        $('#schedule .calendar h2:eq(3) em').remove();
        // 获取当前时间第一天的星期数
        var _week = parseInt(date.getDay());
        var _weeks = ["七", "一", "二", "三", "四", "五", "六"];
        for (var i = 1; i <= days; i++, _week++) {
            // 渲染日期天数
            $('#schedule .calendar h2:eq(0)').append('<em>' + i + '</em>');

            // 渲染星期数
            if (_week > 6) {
                _week = 0;
            }
            $('#schedule .calendar h2:eq(1)').append('<em>' + _weeks[_week] + '</em>');
            var _m = parseInt(_month) + 1;
            var _1 = _year + '' + (_m < 10 ? '0' + _m : _m) + '' + (i < 10 ? '0' + i : i);
            $('#schedule .calendar h2:eq(2)').append('<em id="lunch_' + _1 + '" class="ico1"></em>');
            $('#schedule .calendar h2:eq(3)').append('<em id="dinner_' + _1 + '" class="ico1"></em>');
        }
        if (sche && sche != '') {
            var _scheObj = eval('(' + sche + ')');
            for (var key in _scheObj) {
                var _value = _scheObj[key];
                var _key = key.split('-')[0];
                if (key.indexOf('-1') != -1) {
                    $('#lunch_' + _key).toggleClass('ico1').addClass('ico');
                } else if (key.indexOf('-2') != -1) {
                    $('#dinner_' + _key).toggleClass('ico1').addClass('ico');
                }
            }
        }
    },

    /**
     * 新增档期信息
     */
    insertSchedule: function (dat, type) {
        if (dat != null && dat.length === 8) {
            d_year = dat.substr(0, 4);
            d_month = dat.substr(4, 2);
            d_day = dat.substr(6, 2);
            dat = new Date(d_year, (d_month - 1), d_day);
            dat = dat.getTime();
        }
        if (dat <= new Date(formatDate(new Date(), 'yyyy-MM-dd'))) {
            tip('所选时间不能小于当前时间');
            sys_schedule.isClick = true;
            return;
        }
        var _data = {
            "schedule_date": dat,
            "schedule_type": type
        };
        $.ajax({
            type: "post",
            url: "/htmlWeb/addSchedule.json",
            data: _data,
            error: function (e) {
                console.log('error')
            },
            success: function (ret) {
                $.ajax({
                    type: "get",
                    url: "by/schedule",
                    data: {
                        "user_id": 0
                    },
                    error: function (e) {
                        console.log('error');
                    },
                    success: function (ret1) {
                        sys_schedule.renderSchedule(new Date(d_year, d_month - 1, '01'), ret1.scheduleData);
                        sys_schedule.isClick = true;
                    }
                });
            }
        });
    },

    /**
     * 删除档期信息
     * @param dat 档期时间
     * @param type 当期类型（1-午餐；2-晚宴）
     * @param userId 商家ID
     */
    deleteSchedule: function(dat, type, userId) {
        if (dat != null && dat.length === 8) {
            d_year = dat.substr(0, 4);
            d_month = dat.substr(4, 2);
            d_day = dat.substr(6, 2);
            dat = new Date(d_year, (d_month - 1), d_day);
            dat = dat.getTime();
        }
        if (dat <= new Date(formatDate(new Date(), 'yyyy-MM-dd'))) {
            tip('所选时间不能小于当前时间');
            sys_schedule.isClick = true;
            return;
        }
        $.ajax({
            type: "get",
            url: "htmlWeb/orderUnfinished.json",
            data: {
                "scheduleDate": (d_year + '-' + d_month + '-' + d_day),
                "scheduleType": type,
                "userId": userId
            },
            error: function() {
                console.log('orderUnfinished -> error');
            },
            success: function(rnd) {
                if (rnd && rnd.result > 0) {
                    tip('该档期内有未完成的订单，不允许取消！');
                    sys_schedule.isClick = true;
                } else {
                    var _data = {
                        "schedule_date": dat,
                        "schedule_type": type,
                        "user_id": userId
                    };
                    $.ajax({
                        type: "post",
                        url: "htmlWeb/delSchedule.json",
                        data: _data,
                        error: function (e) {
                            console.log('error')
                        },
                        success: function (ret) {
                            $.ajax({
                                type: "get",
                                url: "by/schedule",
                                data: {
                                    "user_id": 0
                                },
                                error: function (e) {
                                    console.log('error');
                                },
                                success: function (ret1) {
                                    sys_schedule.renderSchedule(new Date(d_year, d_month - 1, '01'), ret1.scheduleData);
                                    sys_schedule.isClick = true;
                                }
                            });
                        }
                    });
                }
            }
        });
    },

    /**
     * 绑定商家档期翻日历事件
     */
    bindDateEvent: function(userId) {
        /**
         * 上一月
         */
        $('html, body').off('click', '#schedule label a:eq(0)').on('click', '#schedule label a:eq(0)', function (e) {
            e.stopPropagation();
            $.ajax({
                type: "get",
                url: "by/schedule",
                data: {
                    "user_id": userId
                },
                error: function (e) {
                    console.log(e);
                },
                success: function (ret) {
                    var $curDate = $('#md_cur_date').val();
                    var preDate = getPreMonth($curDate);
                    var md_show_date = formatDate(preDate, 'yyyy年MM月');
                    var md_hide_date = formatDate(preDate, 'yyyy-MM');
                    $('#schedule label b').text(md_show_date);
                    $('#md_cur_date').val(md_hide_date);
                    sys_schedule.renderSchedule(preDate, ret.scheduleData);
                }
            });
        });

        /**
         * 下一月
         */
        $('html, body').off('click', '#schedule label a:eq(1)').on('click', '#schedule label a:eq(1)', function (e) {
            e.stopPropagation();
            $.ajax({
                type: "get",
                url: "by/schedule",
                data: {
                    "user_id": userId
                },
                error: function (e) {
                    console.log(e);
                },
                success: function (ret) {
                    var $curDate = $('#md_cur_date').val();
                    var nextDate = getNextMonth($curDate);
                    var md_show_date = formatDate(nextDate, 'yyyy年MM月');
                    var md_hide_date = formatDate(nextDate, 'yyyy-MM');
                    $('#schedule label b').text(md_show_date);
                    $('#md_cur_date').val(md_hide_date);
                    sys_schedule.renderSchedule(nextDate, ret.scheduleData);
                }
            });
        });
    },
    selectedDate: '',
    selectedType: '',
    isClick: true,
    /**
     * 绑定页面点击事件
     */
    bindEvents: function() {
        $('html, body').on('mouseover', '#schedule .calendar h2:gt(1) em', function() {
            $(this).css('cursor', 'pointer');
        }).on('click', '#schedule .calendar h2:gt(1) em', function(e) { // 点击指定日期下的“午餐”或者“晚宴”
            e = e || window.event;
            e.stopPropagation();
            if (sys_schedule.isClick) {
                sys_schedule.isClick = false;
                var _curType = $(this).attr('id').split('_')[0] == 'lunch' ? 1 : 2;
                var _curDate = $(this).attr('id').split('_')[1];
                sys_schedule.selectedDate = _curDate;
                sys_schedule.selectedType = _curType;
                if ($(this).attr('class').indexOf('ico1') != -1) { // 该日期未被选择
                    sys_schedule.insertSchedule(sys_schedule.selectedDate, sys_schedule.selectedType);
                } else { // 该日期已被选择
                    sys_schedule.deleteSchedule(sys_schedule.selectedDate, sys_schedule.selectedType, loginUserId);
                }
            }
        });
    }
}

$(function() {
    sys_schedule.init();
    sys_schedule.bindEvents();
});